import {io, Socket} from "socket.io-client";
import {useUserStore} from "@/store/UseUserStore.ts";
import router from "@/router";

export class SocketUtils {

    static socket: Socket;

    static initSocket() {
        // 防止重复调用
        if (this.socket) {
            return;
        }

        // 构建监听
        const baseImUrl = "ws://119.23.144.149:9010";
        console.log("当前通信连接:", baseImUrl)

        this.socket = io(baseImUrl, {
            // 仅使用 Websocket 方式连接
            transports: ["websocket"],

            // 允许跨域访问
            withCredentials: true,

            extraHeaders: {
                // 设置允许的跨域源为全部
                "Access-Control-Allow-Origin": "*"
            },

            // 每一次的通信携带 Token 参数
            query: {token: useUserStore().token}
        });

        // 连接成功时的监听事件
        this.socket.on("connect", () => {
            console.info("连接成功...")
        });

        // 断开连接时的监听事件
        // 断开连接时重连见文档: https://socket.io/zh-CN/docs/v4/client-socket-instance/
        this.socket.on("disconnect", (reason, details) => {
            console.info("连接断开, 开始重连:", reason, details)
        });

        // 连接错误时的监听事件
        // 连接错误时更新凭据见文档: https://socket.io/zh-CN/docs/v4/client-socket-instance/
        this.socket.on("connect_error", (error) => {
            if (this.socket.active) {
                const token = useUserStore().token;
                console.info("连接错误, 开始重连:", error)
                console.info("重新设置 Token:", token)
                if (token) {
                    this.socket.io.opts.query = {token: token};
                } else {
                    // 如果获取不到 Token，跳转到登录页
                    router.push("/auth/login").then();
                }
                // temporary failure, the socket will automatically try to reconnect
            } else {
                // the connection was denied by the server
                // in that case, `socket.connect()` must be manually called in order to reconnect
                console.info("连接错误:", error)
            }
        });

        // 发起连接
        this.socket.connect();
    }
}
